/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tesam.gedeon.controller;

import com.tesam.gedeon.entity.Account;
import com.tesam.gedeon.entity.Country;
import com.tesam.gedeon.entity.Department;
import com.tesam.gedeon.entity.District;
import com.tesam.gedeon.entity.Province;
import com.tesam.gedeon.service.AccountService;
import com.tesam.gedeon.service.CountryService;
import com.tesam.gedeon.service.DepartmentService;
import com.tesam.gedeon.service.DistrictService;
import com.tesam.gedeon.service.ProvinceService;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Sistema
 */
@Controller
public class AccountController {
    
    @Autowired
    SystemUserController system ;
    @Autowired
    AccountService accountService ;
    @Autowired
    CountryService countryService ;
    @Autowired
    DepartmentService departmentService ;   
    @Autowired
    ProvinceService provinceService;  
    @Autowired
    DistrictService districtService ;        
            
    Country country = new Country();
    Department department = new Department();
    Province province = new Province();
    District district = new District();
    
    @RequestMapping(value = "/commercialaccount/index")
    public ModelAndView index(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/commercialaccount/index");
         
        system.loadDataSystem(mv, request);
        
        return mv;
    }
    
    @RequestMapping(value = "/commercialaccount/view")
    public ModelAndView view(@ModelAttribute("Account")Account account,HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/commercialaccount/view");
         
        system.loadDataSystem(mv, request); 
        mv.addObject("ACCOUNT", accountService.getAccountById(account)); 
        
        return mv;
    }
    
    @RequestMapping(value = "/commercialaccount/update")
    public ModelAndView update(@ModelAttribute("Account")Account account,HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/commercialaccount/update");
        system.loadDataSystem(mv, request); 
        
        List<Account> result = accountService.getAccountById(account) ;
        if(result.get(0).getCountryBill().getLongCode() != null){
            country.setCode(result.get(0).getCountryBill().getLongCode().trim());
            department.setCountry(country);
            mv.addObject("department_bill", departmentService.getListByCountry(department)); 
            
            if(result.get(0).getDepartmentBill().getCode() != null){
            
            country.setCode(result.get(0).getCountryBill().getLongCode().trim());
            department.setCode(result.get(0).getDepartmentBill().getCode().trim());
            province.setDepartment(department);
            province.setCountry(country);
            mv.addObject("province_bill", provinceService.getListByDepartmentAndCountry(province));
                if(result.get(0).getProvinceBill().getCode() != null){ 
                   province.setCode(result.get(0).getProvinceBill().getCode().trim());
                   country.setCode(result.get(0).getCountryBill().getLongCode().trim());
                   department.setCode(result.get(0).getDepartmentBill().getCode().trim());
                   district.setProvince(province); 
                   district.setDepartment(department);
                   district.setCountry(country);
                   mv.addObject("district_bill", districtService.getDistrictByProvinceAndDepartmentAndCountry(district));
                }
            }
        }
        
        if(result.get(0).getCountryShipping().getLongCode() != null){
            country.setCode(result.get(0).getCountryShipping().getLongCode().trim());
            department.setCountry(country);
            mv.addObject("department_shipping", departmentService.getListByCountry(department)); 
            if(result.get(0).getDepartmentShipping().getCode() != null){
                country.setCode(result.get(0).getCountryShipping().getLongCode().trim());
                department.setCode(result.get(0).getDepartmentShipping().getCode().trim());
                province.setCountry(country);
                province.setDepartment(department);
                mv.addObject("province_shipping", provinceService.getListByDepartmentAndCountry(province));
                if(result.get(0).getProvinceShipping().getCode() != null){
                country.setCode(result.get(0).getCountryShipping().getLongCode().trim());
                department.setCode(result.get(0).getDepartmentShipping().getCode().trim());
                province.setCode(result.get(0).getProvinceShipping().getCode().trim());
                district.setCountry(country);
                district.setDepartment(department);
                district.setProvince(province);
                mv.addObject("district_shipping", districtService.getDistrictByProvinceAndDepartmentAndCountry(district));
                }
            }
        }
        
        
        mv.addObject("ACCOUNT",result );
        mv.addObject("country_bill", countryService.getListAll());
      
        return mv;
    }
    
    @RequestMapping(value = "/commercialaccount/newsave")
    public ModelAndView savenew(@ModelAttribute("Account")Account account,HttpServletRequest request){
         
        ModelAndView mv = new ModelAndView("/commercialaccount/save"); 
         
        country.setLongCode(request.getParameter("CboCountryBill").toString());
        account.setCountryBill(country); 
        department.setCode(request.getParameter("CboDepartmentBill").toString());
        account.setDepartmentBill(department); 
        province.setCode(request.getParameter("CboProvinceBill").toString());
        account.setProvinceBill(province); 
        district.setCode(request.getParameter("CboDistrictBill").toString());
        account.setDistrictBill(district); 
        
        country = new Country();
        department = new Department();
        province = new Province();
        district = new District();
        country.setLongCode(request.getParameter("CboCountryShipping").toString());
        account.setCountryShipping(country); 
        department.setCode(request.getParameter("CboDepartmentShipping").toString());
        account.setDepartmentShipping(department); 
        province.setCode(request.getParameter("CboProvinceShipping").toString());
        account.setProvinceShipping(province); 
        district.setCode(request.getParameter("CboDistrictShipping").toString()); 
        account.setDistrictShipping(district); 
        
       
        
        mv.addObject("id", accountService.save(account));
        
        return mv ;
    }
    
    @RequestMapping(value = "/commercialaccount/saveupdate")
    public ModelAndView saveupdate(@ModelAttribute("Account")Account account,HttpServletRequest request){
    ModelAndView mv = new ModelAndView("/commercialaccount/save");
     
     country.setLongCode(request.getParameter("CboCountryBill").toString());
        account.setCountryBill(country); 
        department.setCode(request.getParameter("CboDepartmentBill").toString());
        account.setDepartmentBill(department); 
        province.setCode(request.getParameter("CboProvinceBill").toString());
        account.setProvinceBill(province); 
        district.setCode(request.getParameter("CboDistrictBill").toString());
        account.setDistrictBill(district); 
        
        country = new Country();
        department = new Department();
        province = new Province();
        district = new District();
        
        country.setLongCode(request.getParameter("CboCountryShipping").toString());
        account.setCountryShipping(country); 
        department.setCode(request.getParameter("CboDepartmentShipping").toString());
        account.setDepartmentShipping(department); 
        province.setCode(request.getParameter("CboProvinceShipping").toString());
        account.setProvinceShipping(province); 
        district.setCode(request.getParameter("CboDistrictShipping").toString());
        account.setDistrictShipping(district); 
        
       
//         MultipartFile multipart = account.getImageFile();
//        try {
//             File path = new File("C:\\Users\\Sistema\\Desktop\\GedeonMvc\\trunk\\GedeonMvc\\web\\resources\\accountPictures\\");
//             multipart.transferTo(new File(path, multipart.getOriginalFilename()));
//             account.setImageName(multipart.getOriginalFilename());
//        } catch (Exception e) {
//             System.out.println("no se pudo copiar : "+e.getMessage());
//              
//        }
    accountService.update(account);
    mv.addObject("id", account.getId());
    return mv ;
    }
    
    @RequestMapping(value = "/commercialaccount/new")
    public ModelAndView newAccount(@ModelAttribute("Account")Account account,HttpServletRequest request){
        ModelAndView mv = new ModelAndView("/commercialaccount/new");
        
        system.loadDataSystem(mv, request);
        mv.addObject("country", countryService.getListAll());
        
        return mv ;
    }
    
    @RequestMapping(value = "/commercialaccount/delete")
    public ModelAndView delete(@ModelAttribute("Account") Account account){
        ModelAndView mv = new ModelAndView("/commercialaccount/delete");
        
        accountService.delete(account);
        
        return mv ;
    }
    
      @RequestMapping(value = "/commercialaccount/ajax" , method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGet() {

        int cantidadRegistros = 0;
        try {
            List<Account> list = accountService.getListByLimit(0, 20, "ac.name", "asc");

            // ArrayList<Cliente> list = clienteService.getAllClientes();
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();

            if (list.size() > 0) {
                for (Account account : list) {
                    JSONArray arrayPut = new JSONArray();  
                    arrayPut.put(account.getName()); 
                    arrayPut.put(account.getAccountNo());
                    arrayPut.put(account.getPhone()); 
                    arrayPut.put(account.getEmail()); 
                    arrayPut.put(account.getWebsite()); 
                    arrayPut.put(account.getFax()); 
                    arrayPut.put(account.getFoundation()); 
                     
//                    arrayPut.put(account.getCountryBill().getName()); 
//                    arrayPut.put(account.getDepartmentBill().getName());
//                    arrayPut.put(account.getProvinceBill().getName());
//                    arrayPut.put(account.getDistrictBill().getName());
//                    arrayPut.put(account.getEmailBill());
//                    arrayPut.put(account.getZipcodeBill());
//                    arrayPut.put(account.getAddressBill());
//                    
//                    arrayPut.put(account.getCountryShipping().getName());
//                    arrayPut.put(account.getDepartmentShipping().getName());
//                    arrayPut.put(account.getProvinceShipping().getName());
//                    arrayPut.put(account.getDistrictShipping().getName());
//                    arrayPut.put(account.getEmailShipping());
//                    arrayPut.put(account.getZipcodeShipping());
//                    arrayPut.put(account.getAddressShipping());
                    
                    array.put(arrayPut);
                    // cantidadRegistros++;
                }
            }


            cantidadRegistros = accountService.getCountAll();
            json.put("iTotalRecords", cantidadRegistros);
            json.put("iTotalDisplayRecords", cantidadRegistros);
            json.put("aaData", array);

            return json.toString();
        } catch (Exception e) {
            System.out.print("Error - Controller-doAjax:" + e.getMessage());
        }

        return null;
    }
     
      @RequestMapping(value = "/commercialaccount/ajax", method = RequestMethod.POST)
    public @ResponseBody
    String doAjaxPost(HttpServletRequest request) {

        List<Account> listAccount = null;
        int cantidadRegistros = 0;

        String[] columns = {"ac.name", "ac.phone", "ac.email" , "ac.website" , "ac.fax" , "ac.foundation" ,
        "co.name" , "de.name" ,  "pr.name" , "di.name", "ac.emaill_bill" , "ac.zipcode_bill" , "ac.address_bill",
        "co2.name" , "de2.name" ,  "pr2.name" , "di2.name","ac.emaill_shipping" , "ac.zipcode_shipping" , "ac.address_shipping"};
     

        String startLimit = request.getParameter("iDisplayStart");
        String endLimit = request.getParameter("iDisplayLength");
        String dataToSort = columns[Integer.valueOf(request
                .getParameter("iSortCol_0"))];
        String directionOfOrder = request.getParameter("sSortDir_0");
        String textSearch = request.getParameter("sSearch").toUpperCase();

        int _startLimit = 0;
        int _endLimit = 0;

        if (startLimit != null && !startLimit.equals("0")) {

            if (!startLimit.trim().isEmpty()) {
                _startLimit = Integer.valueOf(startLimit);
            }
        }

        if (endLimit != null && !endLimit.equals("0")) {
            if (!endLimit.trim().isEmpty()) {
                _endLimit = Integer.valueOf(endLimit);
            }
        }

        if (textSearch != null) {
            if (!textSearch.trim().isEmpty()) {
                textSearch = textSearch.trim();
                Account account = new Account();
                account.setName(textSearch);
                listAccount = accountService.getListBySearch(_startLimit,_endLimit,"ac.name" , "asc" , account);
                cantidadRegistros = accountService.getCountBySearch(account);
                return accountService.getJsonDataFromArrayList(listAccount, cantidadRegistros);

            }
        }

        listAccount = accountService.getListByLimit(_startLimit,
                (_endLimit), dataToSort, directionOfOrder);

        cantidadRegistros = accountService.getCountAll();

        return accountService.getJsonDataFromArrayList(listAccount, cantidadRegistros);
    }

    
}
